package com.example.xianji.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.activity.Main_newsActivity;
import com.example.xianji.activity.Main_news_detailsActivity;
import com.example.xianji.R;
import com.example.xianji.bean.news;
import com.example.xianji.utils.ImageLoadUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 新闻列表适配器
 */
public class NewsAdapter extends BaseAdapter {
    private Context mContext;
    private ArrayList<news> news_list;
    private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
    private DisplayImageOptions options;

    /*    */

    /**
     * 放每个条目高亮词的索引和长度数组
     */
    /*
     * private ArrayList<JSONObject> arraylist=new ArrayList<JSONObject>();
     * private ArrayList<String> hightName=new ArrayList<String>(); private
     * ArrayList<Integer> hightIndex=new ArrayList<Integer>();
     */
    public NewsAdapter(Context mContext, ArrayList<news> news_list) {
        super();
        this.mContext = mContext;
        this.news_list = news_list;

        options = new DisplayImageOptions.Builder()
                /*
                 * .showImageOnLoading(R.drawable.touxiang)
                 * .showImageForEmptyUri(R.drawable.touxiang)
                 * .showImageOnFail(R.drawable.touxiang)
                 */
                .bitmapConfig(Bitmap.Config.RGB_565)
                // 设置为RGB565比起默认的ARGB_8888要节省大量的内存
                .delayBeforeLoading(100)
                // 载入图片前稍做延时可以提高整体滑动的流畅度
                .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true)
                .displayer(new RoundedBitmapDisplayer(10)).build();

    }

    @Override
    public int getCount() {
        return news_list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        Holder mHolder;
        if (arg1 == null) {
            mHolder = new Holder();
            arg1 = View.inflate(mContext, R.layout.news_listview_item, null);
            mHolder.news_image = (ImageView) arg1.findViewById(R.id.news_image);
            mHolder.news_title = (TextView) arg1.findViewById(R.id.news_title);
            mHolder.news_details = (TextView) arg1
                    .findViewById(R.id.news_details);
            arg1.setTag(mHolder);
        }
        mHolder = (Holder) arg1.getTag();
        String path = new StringBuffer(Contant.news_tupian)
                .append(news_list.get(arg0).getPath())
                .append(news_list.get(arg0).getName()).toString();

        /**
         * 每个条目匹配高亮词的索引和长度数组
         */
        /*
         * JSONArray array1 = new JSONArray();
         *//**
         * 计算每个条目对应高亮词的索引和长度，放入每个条目的数组中 标题
         */
        /*
         * for (int i = 0; i < Main_newsActivity.high_light_word.length(); i++)
         * { try { if (news_list .get(arg0) .getNews_title() .contains(
         * Main_newsActivity.high_light_word.getString(i))) { JSONObject object
         * = new JSONObject(); object.put( "start_pos", news_list .get(arg0)
         * .getNews_title() .indexOf( Main_newsActivity.high_light_word
         * .getString(i))); object.put("str_length",
         * Main_newsActivity.high_light_word .getString(i).length());
         * array1.put(object);
         *
         * news_list.get(arg0).setHight_light_pos(array1);
         *
         * } } catch (JSONException e) {
         * e.printStackTrace(); } }
         *//**
         * 设置具体索引的颜色
         */
        /*
         *
         * SpannableStringBuilder style = new SpannableStringBuilder(news_list
         * .get(arg0).getNews_title());
         *
         * for (int i = 0; i <
         * news_list.get(arg0).getHight_light_pos().length(); i++) {
         *
         * try { JSONObject OBJECT = array1.getJSONObject(i);
         *
         * style.setSpan(new ForegroundColorSpan(Color.RED),
         * OBJECT.getInt("start_pos"), OBJECT.getInt("start_pos") +
         * OBJECT.getInt("str_length"), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
         *
         * } catch (JSONException e) {
         * e.printStackTrace(); }
         *
         * } mHolder.news_title.setText(style);
         */
        /**
         * 设置标题高亮搜索词
         */
        setHightWords(news_list.get(arg0).getNews_title(), arg0,
                mHolder.news_title);
        /**
         * 设置详情高亮搜索词
         */
        setHightWords(news_list.get(arg0).getDescription(), arg0,
                mHolder.news_details);


        // 显式的将checkActualViewSize设为false, 这样图片的缓存也将只会保存一个副本,保证第二次查询时可以直接命中
        ImageViewAware imageaware = new ImageViewAware(mHolder.news_image,
                false);
        String name_path = news_list.get(arg0).getPath()
                + news_list.get(arg0).getName();

        // /清除动画ImageView和Bitmap手动从内存缓存设置
        ImageLoadUtil.loadImageByPath(options, path, imageaware,
                animateFirstListener);

        final int a = arg0;
        arg1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,
                        Main_news_detailsActivity.class);
                intent.putExtra("news_details_id", news_list.get(a).getId());

                intent.putExtra("news", 2);
                mContext.startActivity(intent);
            }
        });
        return arg1;
    }

    /**
     * 设置文字高亮的方法
     *
     * @param title
     * @param index
     * @param textview
     */
    public void setHightWords(String title, int index, TextView textview) {

        /**
         * 每个条目匹配高亮词的索引和长度数组
         */
        JSONArray array1 = new JSONArray();
        /**
         * 计算每个条目对应高亮词的索引和长度，放入每个条目的数组中 标题
         */
        for (int i = 0; i < Main_newsActivity.high_light_word.length(); i++) {
            try {
                if (title.contains(Main_newsActivity.high_light_word
                        .getString(i))) {
                    JSONObject object = new JSONObject();
                    object.put("start_pos", title
                            .indexOf(Main_newsActivity.high_light_word
                                    .getString(i)));
                    object.put("str_length", Main_newsActivity.high_light_word
                            .getString(i).length());
                    array1.put(object);

                    news_list.get(index).setHight_light_pos(array1);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        /**
         * 设置具体索引的颜色
         */
        SpannableStringBuilder style = new SpannableStringBuilder(title);
        for (int i = 0; i < news_list.get(index).getHight_light_pos().length(); i++) {
            try {
                JSONObject OBJECT = array1.getJSONObject(i);
                style.setSpan(new ForegroundColorSpan(Color.RED),
                        OBJECT.getInt("start_pos"), OBJECT.getInt("start_pos")
                                + OBJECT.getInt("str_length"),
                        Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        textview.setText(style);
    }

    class Holder {
        ImageView news_image;
        TextView news_title;
        TextView news_details;
    }

    public static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {
        public static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 200);
                    displayedImages.add(imageUri);
                }
            }
        }
    }
}
